import { memo, useRef } from "react";
import { addEvent, removeEvent, throttle } from "@/utils";

const ColItem = memo(({ index, addColHeight, isActive, height }) => {
  const resizeStartPos = useRef();
  function handleResize(e) {
    e.stopPropagation();
    resizeStartPos.current = e.clientY;
    const _handleMove = throttle(handleMove, 20);
    addEvent(document, "mousemove", _handleMove);
    addEvent(document, "mouseup", handleUp);

    function handleMove(e) {
      const distance = e.clientY - resizeStartPos.current;
      addColHeight(height + distance);
    }

    function handleUp() {
      removeEvent(document, "mousemove", _handleMove);
      removeEvent(document, "mouseup", handleUp);
    }
  }

  return (
    <div
      className={`cr col-item ${isActive ? "active" : ""}`}
      style={{ height: `${height}px`, lineHeight: `${height}px` }}
      data-col={index}
    >
      {index}
      <div
        className="col-resize"
        data-col={index}
        onMouseDown={(e) => handleResize(e)}
      ></div>
    </div>
  );
});

export default ColItem;
